<?php

namespace app\admin\controller;

use app\BaseController;
use app\model\RatingScaleModel;
use app\model\UserModel;
use app\model\wireless\WirelessEvaluationResultModel;
use app\model\wireless\WirelessTaskModel;
use app\model\wireless\WirelessTaskUserModel;
use app\user\service\RatingScaleService as UserRatingScaleService;
use think\App;

class WirelessEvaluation extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 发布任务
     * @return bool|string
     */
    public function PublishTask(): bool|string
    {
        $WirelessTaskModel = new WirelessTaskModel();
        $WirelessTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'uid|用户' => 'require',
                'rating_scale_id' => 'require',
                'name|任务名称' => 'require'
            ]);
            $WirelessTaskUserModel = new WirelessTaskUserModel();
            $time = time();
            $task_id = $WirelessTaskModel->insertGetId([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'rating_scale_id' => $param['rating_scale_id'],
                'user_count' => count($param['uid']),
                'time' => $time,
                'name' => $param['name'],
                'result_read_auth' => implode(',',$param['result_read_auth']??[]),
            ]);
            $TaskUser = [];
            foreach ($param['uid'] as $uid) {
                $TaskUser[] = [
                    'task_id' => $task_id,
                    'uid' => $uid,
                    'rating_scale_id' => $param['rating_scale_id'],
                    'time' => $time
                ];
            }
            $WirelessTaskUserModel->insertAll($TaskUser,200);
            $WirelessTaskModel->commit();
            return success($task_id,'发布成功！');
        } catch (\Exception $e) {
            $WirelessTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 用户编号获取用户信息
     * @return bool|string
     */
    public function userNumberGetUserInfo(): bool|string
    {
        try {
            $user_number = $this->request->param("user_number");
            $UserModel = new UserModel();
            $info = $UserModel->where("user_number",'=', $user_number)->find();
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交无线测评结果
     * @return bool|string
     */
    public function SubmitResults(): bool|string
    {
        $WirelessEvaluationResultModel = new WirelessEvaluationResultModel();
        $WirelessEvaluationResultModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'uid|用户ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'question_answer|用户填写的答案' => 'require',
                'finish_used_time|用户完成用时' => 'require',
            ]);
            $lock = 'submit_wireless_evaluation'.$param['uid'].'task_id'.$param['task_id'];
            if (cache($lock)) throw new \Exception('操作过快，请稍后再试~');
            cache($lock,1,30);
            $WirelessTaskUserModel = new WirelessTaskUserModel();
            //不可重复提交
            $TaskUserInfo = $WirelessTaskUserModel->field('id,uid,is_finish')->where([
                ['task_id','=',$param['task_id']],
                ['uid','=',$param['uid']],
                ['rating_scale_id','=',$param['rating_scale_id']],
            ])->find();
            if (!$TaskUserInfo) throw new \Exception('参数错误！');
            if ($TaskUserInfo['is_finish'] == 1) throw new \Exception('不可重复提交！');
            $UserRatingScaleService = new UserRatingScaleService($this->app);
            if (!$UserRatingScaleService->generateReport([
                'company_id' => $this->userData['company_id'],
                'areas_id' => $this->userData['areas_id'],
                'unit_id' => $this->userData['unit_id'],
                'uid' => $param['uid'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $TaskUserInfo['id'],//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'answer_role' => 1,//答题角色【1 用户，2 家长】
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ], 5))
                throw new \Exception('提交失败！' . $UserRatingScaleService->message);
            $TaskUserInfo->save([
                'is_finish' => 1,
                'result_id' => $UserRatingScaleService->ResultId
            ]);
            $WirelessEvaluationResultModel->commit();
            return success([], '提交成功！');
        } catch (\Exception $e) {
            $WirelessEvaluationResultModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 报告列表
     * @return bool|string
     */
    public function reportList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数量' => 'require'
            ]);
            if (!empty($param['name'])){
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','like','%'.$param['name'].'%']
                ])->column('id');
                if (!empty($uid)){
                    $resultWhere[] = ['uid','in',$uid,'or'];
                }
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_id = $RatingScaleModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','like','%'.$param['name'].'%']
                ])->column('id');
                if (!empty($rating_scale_id)){
                    $resultWhere[] = ['rating_scale_id','in',$rating_scale_id,'or'];
                }
                if (!empty($resultWhere)){
                    $resultWhere[] = ['unit_id','=',$this->userData['unit_id']];
                    $WirelessEvaluationResultModel = new WirelessEvaluationResultModel();
                    $task_id = $WirelessEvaluationResultModel->where($resultWhere)->distinct(true)->column('task_id');
                    if (!empty($task_id)){
                        $where[] = ['id','in',$task_id];
                    }else{
                        $where[] = ['id','=',-1];
                    }
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0){
                if ($param['is_warning'] == 1){
                    $where[] = ['warning_num','>',0];
                }else{
                    $where[] = ['warning_num','=',0];
                }
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $where[] = ['user_complete_num','>',0];
            $WirelessTaskModel = new WirelessTaskModel();
            $query = $WirelessTaskModel->where($where);
            $data = $query->with([
                'user',
                'ratingScale'
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务详情-左测概况
     * @return bool|string
     */
    public function taskLeftSurvey(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $WirelessTaskModel = new WirelessTaskModel();
            $info = $WirelessTaskModel->with([
                'user',
                'ratingScale'
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function taskUser()
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);

        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}